package com.zyk.leetcode;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zhangsan
 * @date 2021/4/5 15:25
 */
public class J50 {

    // https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
    public static char firstUniqChar(String s) {
        char[] str = s.toCharArray();
        HashMap<Character, Integer> countMap = new HashMap<>();
        for (char c : str) {
            countMap.put(c, countMap.getOrDefault(c, 0) + 1);
        }
        for (char c : str) {
            if(countMap.get(c) == 1) {
                return c;
            }
        }
        return ' ';
    }
    // map记录下标, 出现一次记录下标, 出现多次记录-1, 找到不为-1,且值最小的key
    public static char firstUniqChar2(String s) {
        char[] str = s.toCharArray();
        HashMap<Character, Integer> countMap = new HashMap<>();
        for (int i = 0; i < str.length; i++) {
            countMap.put(str[i], countMap.containsKey(str[i])? -1: i);
        }
        char ans = ' ';
        int minIndex = Integer.MAX_VALUE;
        for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
            if(entry.getValue() == -1) {
                continue;
            }
            if(entry.getValue() < minIndex) {
                ans = entry.getKey();
                minIndex = entry.getValue();
            }
        }
        return ans;
    }

    // 有添加顺序的map
    public static char firstUniqChar3(String s) {
        char[] str = s.toCharArray();
        LinkedHashMap<Character, Boolean> map = new LinkedHashMap<>(str.length);
        for (char c : str) {
            map.put(c, !map.containsKey(c));
        }
        for (Map.Entry<Character, Boolean> entry : map.entrySet()) {
            if(entry.getValue()) {
                return entry.getKey();
            }
        }
        return ' ';
    }

    // 从 a~c , 在字符串中找第一个和最后一个位置, 如果相等,代表只出现了一次, 考虑是否index
    // 最后通过index判断是否找到
    public char firstUniqChar4(String s) {
        int index = s.length();
        int first = 0;
        for(char c = 'a'; c <= 'z'; c++) {
            first = s.indexOf(c);
            if(first != -1 && first == s.lastIndexOf(c)) {
                if(index > first) {
                    index = first;
                }
            }
        }
        return index < s.length() ? s.charAt(index) : ' ';
    }

    // for test
    public static void main(String[] args) {
        String str = "abaccdeff";
        System.out.println(firstUniqChar(str));
        System.out.println(firstUniqChar2(str));
    }

}
